package com.sgb.kjwl.view.ui.fragment.self;

import android.content.Context;

import androidx.databinding.DataBindingUtil;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentPersonalRegistrationBinding;
import com.sgb.kjwl.di.self.DaggerSelfFragComponent;
import com.sgb.kjwl.di.self.SelfFragModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.utils.Constants;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.activity.WebActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.RegisterActivity3;
import com.sgb.kjwl.view.ui.activity.self.userInfo.RegistrationWelcomeActivity;
import com.sgb.kjwl.view.widget.SimpleCountDownTimer;
import com.sgb.kjwl.viewmodel.self.RegisterModel3;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PersonalRegistrationFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PersonalRegistrationFragment extends AppFragment {


    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    private String mParam1;
    private String mParam2;

    RegisterActivity3 activity;

    FragmentPersonalRegistrationBinding binding;

    public static final int RequestCodeP = 2;
    @Inject
    RegisterModel3 model3;

    private String isStartTimer = "true";//用于判断是否显示5s倒计时

    private boolean isChecked = true;

    public PersonalRegistrationFragment() {
        // Required empty public constructor
    }


    public static PersonalRegistrationFragment newInstance(String param1, String param2) {
        PersonalRegistrationFragment fragment = new PersonalRegistrationFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerSelfFragComponent.builder()
                .appComponent(appComponent)
                .selfFragModule(new SelfFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_personal_registration, container, false);
        binding.setViewModel(model3);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        binding.tvGetCodeBtn.setOnClickListener(this);
        binding.tvAgreement.setOnClickListener(this);
        binding.ivCheckBox.setOnClickListener(this);

        //初始化按钮为可点击效果
        setSureBtn(isChecked);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_agreement:
                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.LICENCE_URL));
                WebActivity.start(getActivity());
                //WebActivity.start(getActivity(), RequestCodeP,ARG_PARAM1, isStartTimer);
                break;
            case R.id.tv_sure_btn:
                registerValidation();
                break;
            case R.id.tv_get_code_btn:
                codeValidation();
                break;
            case R.id.iv_check_box:
                setSureBtn(!isChecked);
                break;
        }
    }

    private void setSureBtn(boolean isCheck) {
        isChecked = isCheck;
        if (isCheck) {
            binding.ivCheckBox.setImageDrawable(getResources().getDrawable(R.mipmap.icon_check_on));
            binding.tvSureBtn.setBackgroundResource(R.drawable.bg_shap_color_change_2corner);
            binding.tvSureBtn.setEnabled(true);
            binding.tvSureBtn.setOnClickListener(this);
        } else {
            binding.ivCheckBox.setImageDrawable(getResources().getDrawable(R.mipmap.icon_check_off));
            binding.tvSureBtn.setBackgroundResource(R.drawable.bg_shap_color_change_2corner_40);
            binding.tvSureBtn.setEnabled(false);
            binding.tvSureBtn.setOnClickListener(null);
        }
    }


    public void setEnable(boolean enable) {
        binding.tvSureBtn.setEnabled(enable);
    }

    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_LOGIN);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }


    private void codeValidation() {
        if (TextUtils.isEmpty(binding.etMobile.getText().toString())) {
            MToast.showToast(getActivity(), "手机号码不能为空");
            return;
        }
        if (!CheckUtils.isMobileNum(binding.etMobile.getText().toString())) {
            MToast.showToast(getActivity(), "请输入正确手机格式");
            return;
        }

        model3.getCodeModel(binding.etMobile.getText().toString());
    }

    public void getCodeSuccess() {
        SimpleCountDownTimer mCountDownTimerUtils = new SimpleCountDownTimer(getActivity(), binding.tvGetCodeBtn, 60000, 1000); //倒计时1分钟
        mCountDownTimerUtils.start();
    }

    private void registerValidation() {
        if (TextUtils.isEmpty(binding.etMobile.getText().toString())) {
            MToast.showToast(getActivity(), "手机号码不能为空");
            return;
        }
        if (TextUtils.isEmpty(binding.etCode.getText().toString())) {
            MToast.showToast(getActivity(), "短信验证码不能为空");
            return;
        }
        if (binding.etCode.getText().toString().length() != 6) {
            MToast.showToast(getActivity(), "验证码长度为6位数");
            return;
        }
        if (TextUtils.isEmpty(binding.edPwd.getText().toString())) {
            MToast.showToast(getActivity(), "新密码不能为空");
            return;
        }
        if (!CheckUtils.isMobileNum(binding.etMobile.getText().toString())) {
            MToast.showToast(getActivity(), "请输入正确手机格式");
            return;
        }

        //判断是否都成立，都包含返回true
        if (!CheckUtils.isPassword(binding.edPwd.getText().toString())) {
            MToast.showToast(getActivity(), "密码长度应为6-18位字母和数字组合");
            return;
        }
        model3.registerModel(binding.etMobile.getText().toString(),binding.edPwd.getText().toString(),binding.etCode.getText().toString());
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof RegisterActivity3) {
            activity = (RegisterActivity3) context;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        activity = null;
    }

    public void showSuccessDialog() {
        activity.finish();
       /* Intent intent = new Intent();
        intent.putExtra("showPage", "FRAGMENT_SELF");
        MainActivity.start(getActivity(), intent);*/
        RegistrationWelcomeActivity.start(getActivity());
    }

   /* @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);   //this
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeP:
                    binding.txAgreement.setText("已阅读并同意");
                    binding.tvSureBtn.setBackgroundResource(R.drawable.bg_shap_color_change_2corner);
                    binding.tvSureBtn.setEnabled(true);
                    binding.tvSureBtn.setOnClickListener(this);
                    isStartTimer = "false";
                    break;
            }
        }
    }*/
}